import React, { useEffect, useState } from 'react';
import {
  Card,
  Typography,
  Table,
  Button,
  Space,
  Input,
  Select,
  Switch,
  Image,
  Tag,
  Modal,
  message,
  Popconfirm,
  DatePicker,
  Form,
  Row,
  Col
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ReloadOutlined,
  EyeOutlined
} from '@ant-design/icons';
import { useAppDispatch } from '../../store';
import { setBreadcrumbs } from '../../store/slices/uiSlice';
import { Banner } from '../../types';
import bannerService, { BannerListParams } from '../../services/banner.service';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';

const { Title } = Typography;
const { Option } = Select;
const { RangePicker } = DatePicker;

const BannerList: React.FC = () => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const [form] = Form.useForm();

  // 状态管理
  const [banners, setBanners] = useState<Banner[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 搜索参数
  const [searchParams, setSearchParams] = useState<BannerListParams>({
    page: 1,
    limit: 10,
    sort: '-createdAt'
  });

  useEffect(() => {
    dispatch(setBreadcrumbs([
      { title: '轮播图管理' },
      { title: '轮播图列表' },
    ]));
  }, [dispatch]);

  // 加载轮播图数据
  const loadBanners = async (params: BannerListParams = searchParams) => {
    try {
      setLoading(true);
      const response = await bannerService.getBanners(params);
      setBanners(response.data);
      setPagination({
        current: response.pagination.current,
        pageSize: response.pagination.pageSize,
        total: response.pagination.total,
      });
    } catch (error) {
      message.error('加载轮播图列表失败');
      console.error('加载轮播图列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadBanners();
  }, []);

  // 搜索处理
  const handleSearch = (values: any) => {
    const params: BannerListParams = {
      ...searchParams,
      page: 1,
      keyword: values.keyword,
      platform: values.platform,
      isActive: values.isActive,
    };
    setSearchParams(params);
    loadBanners(params);
  };

  // 重置搜索
  const handleReset = () => {
    form.resetFields();
    const params: BannerListParams = {
      page: 1,
      limit: 10,
      sort: '-createdAt'
    };
    setSearchParams(params);
    loadBanners(params);
  };

  // 分页处理
  const handleTableChange = (paginationInfo: any) => {
    const params: BannerListParams = {
      ...searchParams,
      page: paginationInfo.current,
      limit: paginationInfo.pageSize,
    };
    setSearchParams(params);
    loadBanners(params);
  };

  // 切换状态
  const handleStatusChange = async (id: string, isActive: boolean) => {
    try {
      await bannerService.updateBannerStatus(id, isActive);
      message.success(`轮播图已${isActive ? '启用' : '禁用'}`);
      loadBanners();
    } catch (error) {
      message.error('状态更新失败');
      console.error('状态更新失败:', error);
    }
  };

  // 删除轮播图
  const handleDelete = async (id: string) => {
    try {
      await bannerService.deleteBanner(id);
      message.success('删除成功');
      loadBanners();
    } catch (error) {
      message.error('删除失败');
      console.error('删除失败:', error);
    }
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的轮播图');
      return;
    }

    Modal.confirm({
      title: '确认删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个轮播图吗？`,
      onOk: async () => {
        try {
          await bannerService.batchDeleteBanners(selectedRowKeys as string[]);
          message.success('批量删除成功');
          setSelectedRowKeys([]);
          loadBanners();
        } catch (error) {
          message.error('批量删除失败');
          console.error('批量删除失败:', error);
        }
      },
    });
  };

  // 表格列定义
  const columns = [
    {
      title: '轮播图',
      dataIndex: 'image',
      key: 'image',
      width: 120,
      render: (image: string) => {
        console.log('轮播图图片URL:', image); // 添加调试日志

        return (
          <Image
            src={image}
            alt="轮播图"
            width={80}
            height={40}
            style={{ objectFit: 'cover', borderRadius: 4 }}
            fallback=""
            onError={(e) => {
              console.error('图片加载失败:', image, e);
            }}
          />
        );
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
    },
    {
      title: '平台',
      dataIndex: 'platform',
      key: 'platform',
      width: 80,
      render: (platform: string) => {
        const colorMap = {
          mobile: 'blue',
          web: 'green',
          all: 'purple',
        };
        const textMap = {
          mobile: '移动端',
          web: 'Web端',
          all: '全平台',
        };
        return <Tag color={colorMap[platform as keyof typeof colorMap]}>{textMap[platform as keyof typeof textMap]}</Tag>;
      },
    },
    {
      title: '排序',
      dataIndex: 'order',
      key: 'order',
      width: 80,
      sorter: true,
    },
    {
      title: '点击量',
      dataIndex: 'clickCount',
      key: 'clickCount',
      width: 80,
      sorter: true,
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      key: 'isActive',
      width: 100,
      render: (isActive: boolean, record: Banner) => (
        <Switch
          checked={isActive}
          onChange={(checked) => handleStatusChange(record._id, checked)}
          checkedChildren="启用"
          unCheckedChildren="禁用"
        />
      ),
    },
    {
      title: '有效性',
      key: 'isValid',
      width: 80,
      render: (record: Banner) => {
        const now = new Date();
        const startValid = !record.startDate || new Date(record.startDate) <= now;
        const endValid = !record.endDate || new Date(record.endDate) >= now;
        const isValid = record.isActive && startValid && endValid;

        return (
          <Tag color={isValid ? 'success' : 'default'}>
            {isValid ? '有效' : '无效'}
          </Tag>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (createdAt: string) => dayjs(createdAt).format('YYYY-MM-DD HH:mm:ss'),
      sorter: true,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (record: Banner) => (
        <Space>
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => navigate(`/banners/${record._id}`)}
          >
            查看
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => navigate(`/banners/${record._id}/edit`)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个轮播图吗？"
            onConfirm={() => handleDelete(record._id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedKeys: React.Key[]) => {
      setSelectedRowKeys(selectedKeys);
    },
  };

  return (
    <div>
      <Title level={2}>轮播图管理</Title>

      {/* 搜索表单 */}
      <Card style={{ marginBottom: 16 }}>
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 16 }}
        >
          <Form.Item name="keyword">
            <Input
              placeholder="搜索标题或描述"
              prefix={<SearchOutlined />}
              style={{ width: 200 }}
            />
          </Form.Item>
          <Form.Item name="platform">
            <Select placeholder="选择平台" style={{ width: 120 }} allowClear>
              <Option value="mobile">移动端</Option>
              <Option value="web">Web端</Option>
              <Option value="all">全平台</Option>
            </Select>
          </Form.Item>
          <Form.Item name="isActive">
            <Select placeholder="选择状态" style={{ width: 120 }} allowClear>
              <Option value="true">启用</Option>
              <Option value="false">禁用</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button onClick={handleReset}>重置</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      {/* 操作按钮 */}
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => navigate('/banners/create')}
            >
              新增轮播图
            </Button>
            <Button
              danger
              icon={<DeleteOutlined />}
              onClick={handleBatchDelete}
              disabled={selectedRowKeys.length === 0}
            >
              批量删除 ({selectedRowKeys.length})
            </Button>
            <Button
              icon={<ReloadOutlined />}
              onClick={() => loadBanners()}
            >
              刷新
            </Button>
          </Space>
        </div>

        {/* 轮播图表格 */}
        <Table
          columns={columns}
          dataSource={banners}
          rowKey="_id"
          loading={loading}
          rowSelection={rowSelection}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
          onChange={handleTableChange}
          scroll={{ x: 1200 }}
        />
      </Card>
    </div>
  );
};

export default BannerList;
